package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.core.security.AuthJwtTokenSecurityInterceptor;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.CultureInfo;
import cn.stylefeng.guns.modular.business.entity.SubDic;
import cn.stylefeng.guns.modular.business.enums.CultureInfoExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.CultureInfoMapper;
import cn.stylefeng.guns.modular.business.pojo.CultureInfoRequest;
import cn.stylefeng.guns.modular.business.service.CanalSecondClassifyService;
import cn.stylefeng.guns.modular.business.service.CanalThreeClassifyService;
import cn.stylefeng.guns.modular.business.service.CultureInfoService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社会文化业务实现层
 *
 * @author zhangyaowen
 * @date 2021/11/05 15:32
 */
@Service
public class CultureInfoServiceImpl extends ServiceImpl<CultureInfoMapper, CultureInfo> implements CultureInfoService {

    @Resource
    private CanalSecondClassifyService canalSecondClassifyService;
    @Resource
    private CanalThreeClassifyService canalThreeClassifyService;
    @Resource
    private AuthJwtTokenSecurityInterceptor authJwtTokenSecurityInterceptor;
    @Resource
    private SubUseBrowseService subUseBrowseService;
    @Resource
    private LoginUserApi loginUserApi;

	@Override
    public void add(CultureInfoRequest cultureInfoRequest) {
        CultureInfo cultureInfo = new CultureInfo();
        BeanUtil.copyProperties(cultureInfoRequest, cultureInfo);
        this.save(cultureInfo);
    }

    @Override
    public void del(CultureInfoRequest cultureInfoRequest) {
        CultureInfo cultureInfo = this.queryCultureInfo(cultureInfoRequest);
        this.removeById(cultureInfo.getId());
    }

    @Override
    public void edit(CultureInfoRequest cultureInfoRequest) {
        CultureInfo cultureInfo = this.queryCultureInfo(cultureInfoRequest);
        BeanUtil.copyProperties(cultureInfoRequest, cultureInfo);
        this.updateById(cultureInfo);
    }

    @Override
    public CultureInfo detail(CultureInfoRequest cultureInfoRequest) {
        return this.queryCultureInfo(cultureInfoRequest);
    }

    @Override
    public PageResult<Map<String,Object>> findPage(CultureInfoRequest cultureInfoRequest) {
        LambdaQueryWrapper<CultureInfo> wrapper = new LambdaQueryWrapper<>();

        String sciFirst = cultureInfoRequest.getSciFirst();
        String sciSecond = cultureInfoRequest.getSciSecond();

        wrapper.like(ObjectUtil.isNotEmpty(sciFirst), CultureInfo::getSciFirst, sciFirst);
        wrapper.like(ObjectUtil.isNotEmpty(sciSecond), CultureInfo::getSciSecond, sciSecond);
        Page<CultureInfo> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        PageResult<CultureInfo> CultureInfoPageResult = PageResultFactory.createPageResult(sysRolePage);
        List<CultureInfo> CultureInfoList=CultureInfoPageResult.getRows();
        List<Map<String,Object>> mapList=new ArrayList<>();
        PageResult<Map<String,Object>> pageResult = new PageResult<>();
        for(CultureInfo cultureInfo:CultureInfoList){
            Map<String, Object> map = new HashMap<String, Object>();
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.YHWH+cultureInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            map.put("title",cultureInfo.getSciTitle());
            map.put("historyDating",cultureInfo.getHistoryDating());
            map.put("theCommon",cultureInfo.getTheCommon());
            map.put("annalsfrom",cultureInfo.getSciAnnalsfrom());
            mapList.add(map);

        }
        pageResult.setRows(mapList);
        pageResult.setPageSize(CultureInfoPageResult.getPageSize());
        pageResult.setPageNo(CultureInfoPageResult.getPageNo());
        pageResult.setTotalPage(CultureInfoPageResult.getTotalPage());
        pageResult.setTotalRows(CultureInfoPageResult.getTotalRows());
        return pageResult;
    }

    @Override
    public List<CultureInfo> findList(CultureInfoRequest cultureInfoRequest) {
        LambdaQueryWrapper<CultureInfo> wrapper = this.createWrapper(cultureInfoRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/11/05 15:32
     */
    private CultureInfo queryCultureInfo(CultureInfoRequest cultureInfoRequest) {
        CultureInfo cultureInfo = this.getById(cultureInfoRequest.getId());
        if (ObjectUtil.isEmpty(cultureInfo)) {
            throw new ServiceException(CultureInfoExceptionEnum.CULTUREINFO_NOT_EXISTED);
        }
        return cultureInfo;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/11/05 15:32
     */
    private LambdaQueryWrapper<CultureInfo> createWrapper(CultureInfoRequest cultureInfoRequest) {
        LambdaQueryWrapper<CultureInfo> queryWrapper = new LambdaQueryWrapper<>();

        Long id = cultureInfoRequest.getId();
        String sciFirst = cultureInfoRequest.getSciFirst();
        String sciSecond = cultureInfoRequest.getSciSecond();
        String sciThird = cultureInfoRequest.getSciThird();
        String sciFourth = cultureInfoRequest.getSciFourth();
        String sciFifth = cultureInfoRequest.getSciFifth();
        String sciPeriod = cultureInfoRequest.getSciPeriod();
        String historyDating = cultureInfoRequest.getHistoryDating();
        String theCommon = cultureInfoRequest.getTheCommon();
        String sciIntroduce = cultureInfoRequest.getSciIntroduce();
        String sciAnnotation = cultureInfoRequest.getSciAnnotation();
        String sciAnnalsfrom = cultureInfoRequest.getSciAnnalsfrom();
        String sciAnnalspage = cultureInfoRequest.getSciAnnalspage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), CultureInfo::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciFirst), CultureInfo::getSciFirst, sciFirst);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciSecond), CultureInfo::getSciSecond, sciSecond);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciThird), CultureInfo::getSciThird, sciThird);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciFourth), CultureInfo::getSciFourth, sciFourth);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciFifth), CultureInfo::getSciFifth, sciFifth);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciPeriod), CultureInfo::getSciPeriod, sciPeriod);
        queryWrapper.like(ObjectUtil.isNotEmpty(historyDating), CultureInfo::getHistoryDating, historyDating);
        queryWrapper.like(ObjectUtil.isNotEmpty(theCommon), CultureInfo::getTheCommon, theCommon);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciIntroduce), CultureInfo::getSciIntroduce, sciIntroduce);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciAnnotation), CultureInfo::getSciAnnotation, sciAnnotation);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciAnnalsfrom), CultureInfo::getSciAnnalsfrom, sciAnnalsfrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(sciAnnalspage), CultureInfo::getSciAnnalspage, sciAnnalspage);

        return queryWrapper;
    }

    @Override
    public Map<String, Object> toReview(String jmId) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmId, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.YHWH,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        HttpServletResponse httpServletResponse = HttpServletUtil.getResponse();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {
            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();

        } else {
            throw new ServiceException(CultureInfoExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<CultureInfo> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(id)) {
            Map<String, Object> mapLists = new HashMap<>();
            return mapLists;
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), CultureInfo::getId, id);
        List<CultureInfo> CultureInfoList = this.list(queryWrapper);


        List<Map<String, Object>> mapList = new ArrayList<>();
        for (CultureInfo CultureInfo : CultureInfoList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(CultureInfo), Map.class);

            // 获取类的属性
            Field[] declaredFields = CultureInfo.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {
//                String title = "";
                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();
                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名

                        if ("sciIntroduce".equals(field.getName()) || "sciAnnotation".equals(field.getName()) ||"sciTitle".equals(field.getName()) ) {
                            if ("sciTitle".equals(field.getName()) ) {
                                p.put("title", map.get(field.getName()));
                            }else
                            if ("sciAnnotation".equals(field.getName()) ) {
                                p.put("annotation", map.get(field.getName()));
                            }
                            else {
                                p.put(field.getName(), map.get(field.getName()));
                            }
                        }else{
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));
                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }
                    }
                    i++;
                }
                p.put("list", mplist);
                if (i != 1) {
                    mapList.add(p);
                }
            }
        }
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.WH,mapList.get(0).get("title").toString(),userid,request);
        }
        return mapList.get(0);
    }

    @Override
    public List<Map<String,Object>> findAllList(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<CultureInfo> wrapper = createWrapperByCulture(riverList,townList,times,name);
        List<CultureInfo>  list = this.list(wrapper);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(CultureInfo cultureInfo:list) {
            Map<String, Object> map = new HashMap<String, Object>();
//            Map<String, Object> map1 = new HashMap<String, Object>();
//            map = JSONObject.parseObject(JSONObject.toJSONString(CultureInfo), Map.class);

            map.put("title", cultureInfo.getSciTitle());
            map.put("historyDating",cultureInfo.getHistoryDating());
            map.put("theCommon",cultureInfo.getTheCommon());
            map.put("from",cultureInfo.getSciAnnalsfrom() );
            map.put("createTime", DateUtil.format(cultureInfo.getCreateTime(), "yyyy-MM-dd"));
            map.put("type",YunHeKey.YHWH);
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.YHWH+cultureInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            mapList.add(map);
        }
        return mapList;
    }
    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<CultureInfo> createWrapperByCulture(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<CultureInfo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.and(i-> i.like(ObjectUtil.isNotNull(name), CultureInfo::getSciTitle, name).or()
                .like(ObjectUtil.isNotNull(name), CultureInfo::getSciAnnalsfrom, name).or()
                .like(ObjectUtil.isNotNull(name), CultureInfo::getTheCommon, name).or()
                .like(ObjectUtil.isNotNull(name), CultureInfo::getHistoryDating, name).or());
        if( !riverList.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < riverList.size(); i++) {
                    String dicAname = riverList.get(i).getDicAname();
                    wrapper.like(ObjectUtil.isNotEmpty(dicAname), CultureInfo::getXgRiver, dicAname);
                    if (i != riverList.size() - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( !townList.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < townList.size(); i++) {
                    String dicZname = townList.get(i).getDicZname();
                    String dicAname = townList.get(i).getDicAname();
                    wrapper.like(ObjectUtil.isNotEmpty(dicZname), CultureInfo::getXgTown, dicZname);
                    if (i != townList.size() - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( times.length !=0) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < times.length; i++) {
                    String time = times[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), CultureInfo::getSciPeriod, time);
                    if (i != times.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        return queryWrapper;
    }
    
}